﻿using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;

namespace QLTV
{
    /// <summary>
    /// Summary description for SingleApp.
    /// </summary>
    public class Ultilities
    {
        static Forms.frmPleaseWait _wait;
        public static int getNextID(string tenBang)
        {
            string commText = String.Format("SELECT IDENT_CURRENT('{0}') + IDENT_INCR('{0}')", tenBang);
            string connStr = ConfigurationManager.ConnectionStrings["QLTV.Properties.Settings.CrewManagmentConnectionString"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand comm = new SqlCommand(commText, conn);
                return Convert.ToInt32(comm.ExecuteScalar());
            }

        }
        public static int getIDentity(string tenBang)
        {
            string commText = String.Format("SELECT IDENT_CURRENT('{0}')", tenBang);
            string connStr = ConfigurationManager.ConnectionStrings["QLTV.Properties.Settings.CrewManagmentConnectionString"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand comm = new SqlCommand(commText, conn);
                return Convert.ToInt32(comm.ExecuteScalar());
            }

        }

        public struct DateTimeSpan
        {
            private readonly int years;
            private readonly int months;
            private readonly int days;
            private readonly int hours;
            private readonly int minutes;
            private readonly int seconds;
            private readonly int milliseconds;

            public DateTimeSpan(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
            {
                this.years = years;
                this.months = months;
                this.days = days;
                this.hours = hours;
                this.minutes = minutes;
                this.seconds = seconds;
                this.milliseconds = milliseconds;
            }

            public int Years { get { return years; } }
            public int Months { get { return months; } }
            public int Days { get { return days; } }
            public int Hours { get { return hours; } }
            public int Minutes { get { return minutes; } }
            public int Seconds { get { return seconds; } }
            public int Milliseconds { get { return milliseconds; } }

            enum Phase { Years, Months, Days, Done }

            public static DateTimeSpan CompareDates(DateTime date1, DateTime date2)
            {

                if (date2 < date1)
                {
                    var sub = date1;
                    date1 = date2;
                    date2 = sub;
                }

                DateTime current = date2;
                int years = 0;
                int months = 0;
                int days = 0;

                Phase phase = Phase.Years;
                DateTimeSpan span = new DateTimeSpan();

                while (phase != Phase.Done)
                {
                    switch (phase)
                    {
                        case Phase.Years:
                            if (current.Year == 1 || current.AddYears(-1) < date1)
                            {
                                phase = Phase.Months;
                            }
                            else
                            {
                                current = current.AddYears(-1);
                                years++;
                            }
                            break;
                        case Phase.Months:
                            if (current.AddMonths(-1) < date1)
                            {
                                phase = Phase.Days;
                            }
                            else
                            {
                                current = current.AddMonths(-1);
                                months++;
                            }
                            break;
                        case Phase.Days:
                            if (current.AddDays(-1) < date1)
                            {
                                var timespan = current - date1;
                                span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
                                phase = Phase.Done;
                            }
                            else
                            {
                                current = current.AddDays(-1);
                                days++;
                            }
                            break;
                    }
                }

                return span;

            }
        }

        public static int MonthDiff(DateTime end, DateTime start)
        {
            int retVal = 0;

            // Calculate the number of years represented and multiply by 12
            // Substract the month number from the total
            // Substract the difference of the second month and 12 from the total
            retVal = (end.Year - start.Year) * 12;
            retVal = retVal - end.Month;
            retVal = retVal - (12 - start.Month);

            return retVal;
        }
        private static readonly string[] VietnameseSigns = new string[]
            {   "aAeEoOuUiIdDyY",  
                "áàạảãâấầậẩẫăắằặẳẵ",
                "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
                "éèẹẻẽêếềệểễ",
                "ÉÈẸẺẼÊẾỀỆỂỄ",
                "óòọỏõôốồộổỗơớờợởỡ",
                "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
                "úùụủũưứừựửữ",
                "ÚÙỤỦŨƯỨỪỰỬỮ",
                "íìịỉĩ",
                "ÍÌỊỈĨ",
                "đ",
                "Đ",
                "ýỳỵỷỹ",
                "ÝỲỴỶỸ"
                };

        public static string RemoveSign4VietnameseString(string str)
        {

            //Tiến hành thay thế , lọc bỏ dấu cho chuỗi

            for (int i = 1; i < VietnameseSigns.Length; i++)
            {

                for (int j = 0; j < VietnameseSigns[i].Length; j++)

                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);

            }

            return str;

        }



        public static void RunLongThread(System.Threading.ThreadStart _thread)
        {
            Thread lengthyProcessThread = new Thread(_thread) { IsBackground = true };
            lengthyProcessThread.Start();
            _wait = new Forms.frmPleaseWait();
            _wait.ShowDialog();
        }

        #region WORD FUNCTION

        public static Word.ApplicationClass _word = null;
        public static Word.Document doc = null;
        public static void preActive(String path)
        {
            string filename = String.Format(path, Application.StartupPath);
            _word = new Word.ApplicationClass();
            doc = _word.Documents.Open(filename, ReadOnly: true, Visible: true);
        }

        public static void Active()
        {
            doc.Activate();
            _word.Visible = true;
            _word.Activate();
        }
        public static void replaceWord(string oldString, string newString, Word.Document wd)
        {
            foreach (Word.Range myStoryRange in wd.StoryRanges)
            {
                myStoryRange.Find.Text = oldString;
                myStoryRange.Find.Replacement.Text = newString;
                myStoryRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;
                myStoryRange.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);
            }
        }

        // -------------------------------------


        #endregion

        /// <summary>
        /// Imports 
        /// </summary>

        [DllImport("user32.dll")]
        private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern int IsIconic(IntPtr hWnd);

        /// <summary>
        /// GetCurrentInstanceWindowHandle
        /// </summary>
        /// <returns></returns>



        private static IntPtr GetCurrentInstanceWindowHandle()
        {
            IntPtr hWnd = IntPtr.Zero;
            Process process = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(process.ProcessName);
            foreach (Process _process in processes)
            {

                if (_process.Id != process.Id &&
                    _process.MainModule.FileName == process.MainModule.FileName &&
                    _process.MainWindowHandle != IntPtr.Zero)
                {
                    hWnd = _process.MainWindowHandle;
                    break;
                }
            }
            return hWnd;
        }
        /// <summary>
        /// SwitchToCurrentInstance
        /// </summary>
        private static void SwitchToCurrentInstance()
        {
            IntPtr hWnd = GetCurrentInstanceWindowHandle();
            if (hWnd != IntPtr.Zero)
            {

                if (IsIconic(hWnd) != 0)
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }

                SetForegroundWindow(hWnd);
            }
        }

        /// <summary>
        /// Execute a form base application if another instance already running on
        /// the system activate previous one
        /// </summary>
        /// <param name="frmMain">main form</param>
        /// <returns>true if no previous instance is running</returns>
        public static bool Run(System.Windows.Forms.Form frmMain)
        {
            if (IsAlreadyRunning())
            {
                //set focus on previously running app
                SwitchToCurrentInstance();
                return false;
            }
            Application.Run(frmMain);
            return true;
        }

        /// <summary>
        /// for console base application
        /// </summary>
        /// <returns></returns>
        public static bool Run()
        {
            if (IsAlreadyRunning())
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// check if given exe alread running or not
        /// </summary>
        /// <returns>returns true if already running</returns>
        private static bool IsAlreadyRunning()
        {
            string strLoc = Assembly.GetExecutingAssembly().Location;
            FileSystemInfo fileInfo = new FileInfo(strLoc);
            string sExeName = fileInfo.Name;
            bool bCreatedNew;

            mutex = new Mutex(true, "Global\\" + sExeName, out bCreatedNew);
            if (bCreatedNew)
                mutex.ReleaseMutex();

            return !bCreatedNew;
        }

        static Mutex mutex;
        const int SW_RESTORE = 9;
    }
    public class MyArgs : EventArgs
    {

        /// <summary>
        /// danh cho thuyen vien len tau
        /// </summary>
        public string crewID { get; set; }
        /// <summary>
        /// danh cho thuyen vien len tau
        /// </summary>
        /// 
        public string crewIDNextLine { get; set; }
        public int rankID { get; set; }
        /// <summary>
        /// danh cho thuyen vien len tau
        /// </summary>
        /// 
        public string NoiLen { get; set; }

        public string NoiRoi { get; set; }

        public int vesselID { get; set; }
        /// <summary>
        /// danh cho thuyen vien len tau
        /// </summary>
        public DateTime ngayLenTau { get; set; }
        /// <summary>
        /// Danh cho thuyen vien xuong tau
        /// </summary>
        public int hopdong { get; set; }
        /// <summary>
        /// Danh cho thuyen vien xuong tau
        /// </summary>
        public DateTime ngayxuong { get; set; }

        //string crewID, int vesselID, DateTime ngayLenTau, int hopDong DateTime ngayXuong

    }
}
